package com.yanqu.road.server.cmd.union.cross.parergon;

import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.union.Parergon;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;

import java.math.BigInteger;

@Cmd(code = Protocol.S_UNION_PARERGON_PRE_BUY_PRODUCT_FROM_CROSS, desc = "预购买")
public class PreBuyCmdFromCross extends AbstractCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {

        CrossUnionProto.ParergonPreBuyCrossRespMsg respMsg = CrossUnionProto.ParergonPreBuyCrossRespMsg.parseFrom(packet.getBytes());

        long price = respMsg.getPrice();

        if(price > 0){
            Property property = new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(price));
            boolean result = player.getModule(CurrencyModule.class).currencyIsEnough(property);
            if (!result) {
                ret = GameErrorCode.E_BAG_INGOTS_NO_ENOUGH;
                return;
            }
            player.getModule(PreReduceModule.class).preReduce(property);
        }

        CrossUnionProto.ParergonBuyCrossReqMsg.Builder crossReqMsg = CrossUnionProto.ParergonBuyCrossReqMsg.newBuilder();
        crossReqMsg.setBussinessId(respMsg.getBussinessId());
        crossReqMsg.setPrice(price);
        crossReqMsg.setProductId(respMsg.getProductId());
        player.sendPacket(Protocol.C_UNION_PARERGON_BUY_PRODUCT, crossReqMsg);

    }

    @Override
    public void sendData(GamePlayer player) {
        if(ret != 0){
            Parergon.BuyProductRespMsg.Builder respMsg = Parergon.BuyProductRespMsg.newBuilder();
            respMsg.setRet(ret);
            player.sendPacket(Protocol.U_UNION_PARERGON_BUY_PRODUCT, respMsg);
        }
    }
}
